package helpers;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.util.regex.Pattern;
import java.util.zip.ZipOutputStream;

import javax.servlet.ServletContext;

import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileReadChannel;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileWriteChannel;
import com.google.appengine.api.files.GSFileOptions.GSFileOptionsBuilder;
import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesServiceFactory;

public class GoogleStorageHelper {

	public static final String BUCKETNAME = "static.hoantocxoan.com";
	private static FileService fileService = FileServiceFactory
			.getFileService();

	public static String getAliasDetail(String str) {
		if (str != null)
			str = str.replace(".html", "");
		else
			str = "";
		return str;
	}

	public static int getWidthImage(String link) {
		URL url;
		int width = 0;
		try {
			url = new URL(link);

			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setDoOutput(true);
			connection.setRequestMethod("GET");
			connection.setRequestProperty("Referer", "aa");
			connection
					.setRequestProperty("User-Agent",
							"curl/7.9.8 (i686-pc-linux-gnu) libcurl 7.9.8 (OpenSSL 0.9.6b) (ipv6 enabled)");
			InputStream is = connection.getInputStream();

			ByteArrayOutputStream buffer = new ByteArrayOutputStream();

			int length;
			byte[] b = new byte[2048];
			byte[] oldImageData = null;

			while ((length = is.read(b)) != -1) {
				buffer.write(b, 0, length);
			}
			buffer.flush();

			oldImageData = buffer.toByteArray();
			Image oldImage = ImagesServiceFactory.makeImage(oldImageData);
			width = oldImage.getWidth();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return width;
	}

	public static String getContentPhp(String pathFile,
			ServletContext srevletContext) {
		InputStream is = srevletContext.getResourceAsStream(pathFile);
		StringBuffer read = new StringBuffer();
		try {
			InputStreamReader in = new InputStreamReader(is, "utf-8");

			char[] buf = new char[102102];

			int numRead = 0;
			while ((numRead = in.read(buf)) != -1) {
				String readData = String.valueOf(buf, 0, numRead);
				read.append(readData);
				buf = new char[102102];
			}
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return read.toString();
	}

	/* get file extension from file name */
	public static String getExtension(String fileName) {
		String extension = "";
		int i = fileName.lastIndexOf(".");
		int p = Math.max(fileName.lastIndexOf("/"), fileName.lastIndexOf("\\"));
		if (i > p) {
			extension = fileName.substring(i + 1);
		}
		if (extension.equals("css")) {
			extension = "text/css";
		} else if (extension.equals("js")) {
			extension = "text/javascript";
		} else if (extension.equals("png")) {
			extension = "image/png";
		} else if (extension.equals("jpeg") || extension.equals("jpg")) {
			extension = "image/jpeg";
		} else if (extension.equals("gif")) {
			extension = "image/gif";
		}
		return extension;
	}

	/*
	 * get list file by application from google storage
	 */
	public static String[] getListFile(String prefix) throws IOException {

		String baseUrl = "http://storagecloudmanager.appspot.com/?bucket=/gs/static.hoantocxoan.com&prefix="
				+ prefix;
		URL my_url = new URL(baseUrl);
		BufferedReader br = new BufferedReader(new InputStreamReader(
				my_url.openStream()));
		String strTemp = "";
		String content = "";
		while (null != (strTemp = br.readLine())) {
			content += strTemp;
		}
		String[] listFiles = content.split(",");
		return listFiles;
	}

	/*
	 * Upload file to google storage
	 */
	public static void uploadGoogleStorage(String fileName, String extension,
			ByteArrayOutputStream baos) throws IOException {
		GSFileOptionsBuilder optionsBuilder = new GSFileOptionsBuilder()
				.setBucket(BUCKETNAME).setKey(fileName.trim())
				.setMimeType(extension).setAcl("public-read");
		AppEngineFile writableFile = fileService.createNewGSFile(optionsBuilder
				.build());
		FileWriteChannel writeChannel = fileService.openWriteChannel(
				writableFile, true);
		writeChannel.write(ByteBuffer.wrap(baos.toByteArray()));
		writeChannel.closeFinally();
	}

	/*
	 * Read file from google storage and compare to zip
	 */
	public static void readFileGoogleStorage(String fileName,
			ZipOutputStream zos) {
		try {

			AppEngineFile readableFile = new AppEngineFile(fileName);
			FileReadChannel readChannel = fileService.openReadChannel(
					readableFile, false);

			InputStream is = Channels.newInputStream(readChannel);
			int nRead;
			byte[] buffer = new byte[10240];
			/*
			 * put to byte array output stream to work with google storage
			 */
			while ((nRead = is.read(buffer, 0, buffer.length)) != -1) {
				zos.write(buffer, 0, nRead);
			}
		} catch (Exception e) {
			e.printStackTrace(System.err);
		}
	}
	
	/*
	 * Read file from google storage
	 */
	public static String readFileGoogleStorage(String fileName) {
		String content = "";
		try {

			FileService fileService = FileServiceFactory.getFileService();
			AppEngineFile readableFile = new AppEngineFile(fileName);
			FileReadChannel readChannel = fileService.openReadChannel(
					readableFile, false);

			InputStream is = Channels.newInputStream(readChannel);
			ByteArrayOutputStream tempBAOS = new ByteArrayOutputStream();

			int length;
			byte[] buffer = new byte[10240];
			while ((length = is.read(buffer, 0,
					buffer.length)) != -1) {
				tempBAOS.write(buffer, 0, length);
			}
			
			content = new String(tempBAOS.toByteArray());
		} catch (Exception e) {
			e.printStackTrace(System.err);
		}
		
		return content;
	}

}
